package com.example.foods.controller;

import com.example.foods.domain.AdminInfo;
import com.example.foods.domain.AjaxResult;
import com.example.foods.domain.FoodsInfo;
import com.example.foods.service.FoodsService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/foods")
public class FoodsController extends BaseController{

    @Resource
    private FoodsService foodsService;

    @PostMapping("/add")
    public AjaxResult addFoods(@RequestBody @Valid FoodsInfo foodsInfo, BindingResult bindingResult, HttpSession httpSession){
        if(bindingResult.hasFieldErrors()){
            return AjaxResult.error(-1, "请求无效 ! ");
        }
        AjaxResult ajaxResult=null;
       //当前登录系统的管理员
        AdminInfo adminInfo=super.findCurrentAdminInfo(httpSession);
        try {
            boolean result=this.foodsService.addFoods(foodsInfo,adminInfo);
            ajaxResult=AjaxResult.ok(result);
        } catch (Exception e) {
            ajaxResult= AjaxResult.
                    error(-1,e.getMessage());
        }
        return ajaxResult;
    }
    //查询所有鲜花
    @GetMapping("/foodall")
    public AjaxResult findfood(){
        List<FoodsInfo> allFoods = this.foodsService.findall();
        return AjaxResult.ok(allFoods);
    }
    @GetMapping("/deletflowers/{id}")
    public void deleteflowers(@PathVariable int id, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        int count = this.foodsService.dleteflowers(id);
        //重定向
        String redirectUrl = "http://localhost:8080/foods/foods_list.html";
        // return "redirect:" + redirectUrl; // 这在纯Servlet中不会工作
        response.sendRedirect(redirectUrl);
    }
}
